package org.toycode.logindemo.service.impl;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.toycode.logindemo.entity.SystemUser;
import org.toycode.logindemo.service.SecurityServiceRemote;
import org.toycode.logindemo.service.SolrServiceRemote;

/**
 * This class implements the security relevant <em>remote</em> services.
 *
 * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
 * @version 1.0.0.1, Aug 19, 2009
 */
@Stateless
public class SecurityServiceBean implements SecurityServiceRemote {

    /**
     * entity manager.
     */
    @PersistenceContext(name = "loginDemoPU")
    private EntityManager em;
    /**
     * logger.
     */
    private Logger logger = LoggerFactory.getLogger(SecurityServiceBean.class);
    @EJB(lookupName="org.toycode.logindemo.service.SolrServiceRemote")
    private SolrServiceRemote solrService;

    /**
     * {@inheritDoc}
     */
    @Override
    public void addUser(final SystemUser user) {
        logger.debug("Adding a new user[name=" + user.getName() + "]....");
        em.persist(user);
        final String home = System.getProperty("solr.solr.home");
        user.setMsWordPath(home + "/../sample1.doc");

//        solrService.index(user);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public SystemUser getUserByName(final String userName) {
        final Query query = em.createNamedQuery("findUserByName");
        query.setParameter("userName", userName);

        try {
            return (SystemUser) query.getSingleResult();
        } catch (final NoResultException ex) {
            return null;
        }
    }
}
